package com.kd.xjoa.scheduled.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kd.xjoa.scheduled.domain.KDDictionary;
import com.kd.xjoa.scheduled.domain.LedgerAssign;
import com.kd.xjoa.scheduled.domain.SumCompCheckDaily;
import com.kd.xjoa.scheduled.domain.WordCombination;
import com.kd.xjoa.scheduled.mapper.DictionaryMapper;
import com.kd.xjoa.scheduled.mapper.SumCheckDailyMapper;
import com.kd.xjoa.scheduled.search.bean.IndexParam;
import com.kd.xjoa.scheduled.search.bean.IndexResult;
import com.kd.xjoa.scheduled.search.utils.IndexSearchUtil;
import com.kd.xjoa.scheduled.service.ScheduledService;
import com.kd.yq.common.utils.CommonUtils;

@Service
public class ScheduledServiceImpl implements ScheduledService {
	
	private static final Log logger = LogFactory.getLog(ScheduledServiceImpl.class);

	@Autowired
	private SumCheckDailyMapper sumCheckDailyMapper;
	
	@Autowired
	private DictionaryMapper dictionaryMapper;
	
	private static final String DIC_LEDGER_YPE="db_oltp.tb_trs_ledger_assign.ledger_type";
	
	public void totalCombMonitor() {
		Integer snapDate = Integer.valueOf(CommonUtils.getNowDateStringOf8());
		String regex = "\\|";
		IndexParam param = null;
		StringBuffer wordsb = null;
		String[] words = null;
		int totalCounts = 0;
		List<SumCompCheckDaily> list = new ArrayList<SumCompCheckDaily>();
		try {
			List<WordCombination> combs = sumCheckDailyMapper.listWordCombination();
			if(CommonUtils.isBlank(combs)){
				return;
			}
			SumCompCheckDaily sumCompCheckDaily = null;
			for (WordCombination wordCombination : combs) {
				if(StringUtils.isBlank(wordCombination.getCn_words())){
					continue;
				}
				sumCompCheckDaily = new SumCompCheckDaily();
				param = new IndexParam();
				wordsb = new StringBuffer();
				words = wordCombination.getCn_words().split(regex);
				for (int i = 0; i < words.length; i++) {
					if(i > 150) break;
					wordsb.append(words[i]).append(",");
				}
				if(wordsb.length() > 0){
					wordsb.deleteCharAt(wordsb.length()-1);
				}
				param.setContent(wordsb.toString());
				param.setPercentage(1);
				//统计总数
				totalCounts = indexSearch(param);
				//返回结构为-1说明索引调用失败
				if(totalCounts == -1){
					logger.error("zt:"+wordCombination.getComb_desc()+",words:"+wordsb.toString()+",index search error, result null ");
					continue;
				}
				logger.info("zt:"+wordCombination.getComb_desc()+"result counts:"+totalCounts);
				sumCompCheckDaily.setSnap_date(snapDate);
				sumCompCheckDaily.setComp_id(wordCombination.getComb_comp_id());
				//看郭经理提供的shell脚本，专题设置的为1，来源类型（fb、wx、wb等）设置的为2
				sumCompCheckDaily.setCheck_item_group("1");
				sumCompCheckDaily.setCheck_item(String.valueOf(wordCombination.getComb_no()));
				sumCompCheckDaily.setTotal_amt(totalCounts);
				list.add(sumCompCheckDaily);
			}
		} catch (Exception e) {
			logger.error("totalCombMonitor error ");
			e.printStackTrace();
		}finally{
			if(CommonUtils.isNotBlank(list)){
				int result = sumCheckDailyMapper.batchAddSumCompCheckDaily(list);
				logger.info("totalCombMonitor, repalce into success,counts: "+result);
			}
		}
		
	}



	public void totalBussinessTypeMonitor() {
		// TODO Auto-generated method stub
		SumCompCheckDaily sumCompCheckDaily = null;
		StringBuffer sourceSb = null;
		List<Integer> sourceList = null;
		IndexParam param = null;
		int totalCounts = 0;
		//记录非网站数据的数量
		int otherCounts = 0;
		Integer snapDate = Integer.valueOf(CommonUtils.getNowDateStringOf8());
		List<SumCompCheckDaily> list = new ArrayList<SumCompCheckDaily>();
		try {
			List<KDDictionary> dicList = dictionaryMapper.getDictionaryByColName(DIC_LEDGER_YPE);
			if(CommonUtils.isBlank(dicList)){
				return;
			}
			List<LedgerAssign> assignList = sumCheckDailyMapper.listLedgerAssign();
			if(CommonUtils.isBlank(assignList)){
				return;
			}
			for (KDDictionary dictionary : dicList) {
				//网源类型数据字典中网站的值为14
				if(dictionary == null || StringUtils.isBlank(dictionary.getCol_key()) || "14".equals(dictionary.getCol_key())){
					continue;
				}
				sourceList = new ArrayList<Integer>();
				for (LedgerAssign ledgerAssign : assignList) {
					if(ledgerAssign == null || ledgerAssign.getLedger_type() == null){
						continue;
					}
					if(ledgerAssign.getLedger_type().intValue() == Integer.valueOf(dictionary.getCol_key()).intValue()){
						sourceList.add(ledgerAssign.getLedger_id());
					}
				}
				sourceSb = new StringBuffer();
				for (Integer source : sourceList) {
					sourceSb.append(source.toString()).append(",");
				}
				if(sourceSb.length() > 0){
					sourceSb.deleteCharAt(sourceSb.length()-1);
				}
				param = new IndexParam();
				param.setSource(sourceSb.toString());
				//统计总数
				totalCounts = indexSearch(param);
				//返回结构为-1说明索引调用失败
				if(totalCounts == -1){
					logger.error("sourceType:"+dictionary.getCol_value()+",index search error, result null ");
					continue;
				}
				logger.info("sourceType:"+dictionary.getCol_value()+", result counts:"+totalCounts);
				
				sumCompCheckDaily = new SumCompCheckDaily();
				sumCompCheckDaily.setSnap_date(snapDate);
				sumCompCheckDaily.setComp_id("comp000000000000");
				//看郭经理提供的shell脚本，专题设置的为1，来源类型（fb、wx、wb等）设置的为2
				sumCompCheckDaily.setCheck_item_group("2");
				sumCompCheckDaily.setCheck_item(dictionary.getCol_value());
				sumCompCheckDaily.setTotal_amt(totalCounts);
				list.add(sumCompCheckDaily);
				
				otherCounts += totalCounts;
			}
			//查询只传时间参数的索引数据
			int nowAllCounts = indexSearch(new IndexParam());
			if(nowAllCounts != -1 && nowAllCounts >= otherCounts){
				SumCompCheckDaily otherSum = new SumCompCheckDaily();
				otherSum.setSnap_date(snapDate);
				otherSum.setComp_id("comp000000000000");
				//看郭经理提供的shell脚本，专题设置的为1，来源类型（fb、wx、wb等）设置的为2
				otherSum.setCheck_item_group("2");
				//网站数据字典中的值为14
				otherSum.setCheck_item("网站");
				//网站的数量=所有数量-平台数量
				otherSum.setTotal_amt(nowAllCounts-otherCounts);
				list.add(otherSum);
			}
		} catch (Exception e) {
			logger.info("totalBussinessTypeMonitor error ");
			e.printStackTrace();
		}finally{
			if(CommonUtils.isNotBlank(list)){
				int result = sumCheckDailyMapper.batchAddSumCompCheckDaily(list);
				logger.info("totalBussinessTypeMonitor, repalce into success,counts: "+result);
			}
		}
	}
	
	private int indexSearch(IndexParam param){
		//初始化查询时间
		initDateTime(param);
		param.setPageNum(1);
		param.setPageSize(1);
		//搜索
		IndexResult result = IndexSearchUtil.search(param);
		if(result == null){
			logger.error("index search error, result null ");
			return -1;
		} 
		if(result.getCode() != 200){
			logger.error("index search error, " + result.toString());
			return -1;
		}
		return result.getData()!=null?result.getData().getTotalElements():-1;
	}
	

	private void initDateTime(IndexParam param){
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowStr = sdf.format(now);
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long startTime = null;
		try {
			startTime = sdf2.parse(nowStr+" 00:00:00").getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		param.setStartTime(startTime);
		param.setEndTime(now.getTime());
	}


}
